package yhao.infra.feature.alipay.core.request.pay;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.request.AlipayTradeWapPayRequest;
import com.alipay.api.response.AlipayTradeWapPayResponse;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import yhao.infra.feature.alipay.core.AliPayService;
import yhao.infra.feature.alipay.core.request.BasePayRequest;

import javax.servlet.http.HttpServletResponse;
import java.util.Date;

/**
 * 手机网站支付接口2.0
 * @see <a href="https://docs.open.alipay.com/api_1/alipay.trade.wap.pay/">更多细节</a>
 */
public class PayWapRequest extends BasePayRequest<AlipayTradeWapPayResponse> {
    private String product_code;//产品销售码
    private String time_expire;//绝对超时时间
    private String returnInfo;  //回调参数

    public PayWapRequest(String out_trade_no, String total_amount, String subject, Date empireTime, String url) {
        super(out_trade_no, total_amount, subject,url);
        this.product_code = "QUICK_WAP_PAY";
        this.time_expire = DateFormatUtils.format(empireTime, "yyyy-MM-dd HH:mm");
    }

    public void setReturnInfo(String returnInfo) {
        this.returnInfo = returnInfo;
    }

    public String getProduct_code() {
        return product_code;
    }

    public String getTime_expire() {
        return time_expire;
    }

    public String getReturnInfo() {
        return returnInfo;
    }

    public void doRequestAndWriteToHttpResponse(HttpServletResponse httpResponse
            ,AliPayService aliPayService) throws Exception {
        AlipayTradeWapPayResponse response = doRequest(aliPayService);
        if(response==null){
            return;
        }
        httpResponse.setContentType("text/html;charset=" + alipayConfig.getCharset());
        httpResponse.getWriter().write(response.getBody());//直接将完整的表单html输出到页面
        httpResponse.getWriter().flush();
        httpResponse.getWriter().close();
    }

    @Override
    protected AlipayTradeWapPayResponse doRequest(){
        AlipayTradeWapPayRequest aliPayRequest = new AlipayTradeWapPayRequest();//创建API对应的request
        String returnParam = StringUtils.isNotBlank(returnInfo)?("?"+returnInfo):"";
        aliPayRequest.setReturnUrl(alipayConfig.getReturnUrl() + returnParam);
        aliPayRequest.setNotifyUrl(alipayConfig.getNotifyUrlPre()+this.getNotifyUrl());//在公共参数中设置回跳和通知地址
        aliPayRequest.setBizContent(JSONObject.toJSONString(this));//填充业务参数

        String method = logRequest(aliPayRequest);
        try {
            return alipayClient.pageExecute(aliPayRequest); //调用SDK生成表单
        } catch (AlipayApiException e) {
            logger.error(method+getOut_trade_no(), e.getMessage());
        }
        return null;
    }
}